import { Injectable, Logger } from '@nestjs/common';
import { HttpService } from '@nestjs/axios';
import { CachePerformance } from 'src/common/decorators/performance.decorator';
import { catchError, firstValueFrom, map, timeout } from 'rxjs';

@Injectable()
export class CommonHttpService {
  private readonly logger = new Logger(CommonHttpService.name);
  private readonly DEFAULT_TIMEOUT = 10000; // 10秒超时
  private readonly cache = new Map<string, { data: any; timestamp: number }>(); // 简单内存缓存
  private readonly CACHE_TTL = 5 * 60 * 1000; // 5分钟缓存

  constructor(private readonly http: HttpService) {}

  @CachePerformance('HTTP_GET')
  async get<T = any>(
    url: string,
    params?: any,
    headers?: Record<string, string>,
    useCache = false,
  ): Promise<T> {
    // 生成缓存键
    const cacheKey = useCache ? `${url}_${JSON.stringify(params)}` : null;

    // 检查缓存
    if (cacheKey && this.cache.has(cacheKey)) {
      const cached = this.cache.get(cacheKey)!;
      if (Date.now() - cached.timestamp < this.CACHE_TTL) {
        this.logger.debug(`Cache hit for ${url}`);
        return cached.data;
      } else {
        this.cache.delete(cacheKey); // 清除过期缓存
      }
    }

    const result = await firstValueFrom(
      this.http.get<T>(url, { params, headers }).pipe(
        timeout(this.DEFAULT_TIMEOUT),
        map((res: any) => res.data),
        catchError((error) => {
          this.logger.error(
            `GET ${url} failed`,
            error?.response?.data || error.message,
          );
          throw error;
        }),
      ),
    );

    // 存储到缓存
    if (cacheKey && result) {
      this.cache.set(cacheKey, { data: result, timestamp: Date.now() });
    }

    return result;
  }

  async post<T = any>(
    url: string,
    data: any,
    headers?: Record<string, string>,
  ): Promise<T> {
    return await firstValueFrom(
      this.http.post<T>(url, data, { headers }).pipe(
        timeout(this.DEFAULT_TIMEOUT),
        map((res: any) => res.data),
        catchError((error) => {
          this.logger.error(
            `POST ${url} failed`,
            error?.response?.data || error.message,
          );
          throw error;
        }),
      ),
    );
  }

  /**
   * 清除缓存
   */
  clearCache(): void {
    this.cache.clear();
  }

  /**
   * 清除过期缓存
   */
  clearExpiredCache(): void {
    const now = Date.now();
    for (const [key, value] of this.cache.entries()) {
      if (now - value.timestamp >= this.CACHE_TTL) {
        this.cache.delete(key);
      }
    }
  }

  // 可扩展 put、delete 等方法
}
